
#import "Controller.h"

/* Global Variables  */

	char	directoryName[MAXPATHLEN + 1] = "/";
	BOOL	first=YES;

/* c subroutines  */

static BOOL isOK(const char *s)
{
	return (!s[0] || s[0] == '.') ? NO : YES;
}


@implementation Controller

- init
{
	[super init];
	return self;
}

- appDidInit:sender
{
	[browserView setPath:"/"];
	[browserView setTitle:directoryName ofColumn:0];
	[browserView loadColumnZero];
	[browserView setTarget:self];
	[browserView setAction:@selector(changeFile:)];
	[browserView setDoubleAction:@selector(selectFile:)];
	return self;
}

- changeFile:sender
{
	const char	*file;
	char		dummy[MAXPATHLEN + 1];
	char		*path;
	char  		pathfile[MAXPATHLEN + 1];
	id			cell;
	
	cell = [[sender matrixInColumn:[sender lastColumn]] selectedCell];
	
	path = [sender getPath:dummy toColumn:[sender lastColumn]];
	
	strcpy(pathfile, path);
	strcat(pathfile, "/");

	file = [cell stringValue];

	if (file)
	{
		strcat(pathfile, file);	
	}

	[selTextView setStringValue:""];
	[curTextView setStringValue:pathfile];
	return self;
}

- selectFile:sender
{
	const char	*file;
	char		dummy[MAXPATHLEN + 1];
	char		*path;
	char  		pathfile[MAXPATHLEN + 1];
	id			cell;
	
	cell = [[sender matrixInColumn:[sender lastColumn]] selectedCell];
	
	path = [sender getPath:dummy toColumn:[sender lastColumn]];
	
	strcpy(pathfile, path);
	strcat(pathfile, "/");

	file = [cell stringValue];

	if (file)
	{
		strcat(pathfile, file);	
	}

	[curTextView setStringValue:""];
	[selTextView setStringValue:pathfile];
	return self;
}


- (int)browser:sender fillMatrix:matrix inColumn:(int)column
{
	struct 	stat buf;
	DIR		*dirp;
	struct 	direct *dp;
	int		count = 0;
	char 	file[MAXPATHLEN + 1], *test;
	
	test = [sender getPath:file toColumn:column];
			
	if (!first)
	{
		strcpy(directoryName, file);
	}
	else
	{
		first = NO;
	}
	
	dirp = opendir(directoryName);

	for (dp = readdir(dirp); dp !=NULL; dp = readdir(dirp))
		if(isOK(dp->d_name))
		{
			[matrix renewRows:count+1 cols:1];
			[[matrix cellAt:count :0] setStringValue:dp->d_name];
			[[matrix cellAt:count :0] setLoaded:YES];

			strcpy(file, directoryName);
			strcat(file, "/");
			strcat(file, dp->d_name);
			stat(file, &buf);
			if ((buf.st_mode & S_IFMT) != S_IFDIR)
				[[matrix cellAt:count :0] setLeaf:YES];
			count++;
		}
		closedir(dirp);

		return count;
}

@end
